import React, { Component } from 'react';
import { connect } from 'dva';
// import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import {
  Alert,
  Card,
  List,
  Input,
  Button,
  InputNumber,
  message,
} from 'antd';
// import Login from '@/components/Login';
import styles from './GoodsList.less';
import Ellipsis from '@/components/Ellipsis';
// import area from "../../assets/area";
import router from 'umi/router';

@connect(({ order, loading }) => ({
  order,
  loading: loading.models.order,
}))
class GoodsListPage extends Component {
  state = {
  };

  componentDidMount() {
    message.config({
      top: 200,
      duration: 2,
      maxCount: 3,
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'order/getGoodsList',
      payload: {
        name:''
      },
    });
  }

  handleDone = () => {
    const that = this;
    const orderLineVOList = [];
    let totalCount = 0;
    let totalAmount = 0.0;
    for(let i=0;i<this.goodsList.length;i++){
      const item = this.goodsList[i];
      totalCount += item.quantity?item.quantity:0;
      totalAmount += item.quantity?item.quantity*item.salePrice:0;
      const orderLine = {
        quantity:item.quantity?item.quantity:0,
        commodityId:item.id,
        commodityName:item.name,
        commodityNumber:item.number,
        commodityCategoryCode:item.category,
        commodityCategoryName:item.categoryName,
        commodityBrandCode:item.brandCode,
        commodityBrandName:item.brandName,
        unitPrice:item.salePrice,
        imgUrl:item.imgUrl,
        amount:item.quantity?item.quantity*item.salePrice:0,
      };
      if(item.quantity && item.quantity>0){
        orderLineVOList.push(orderLine);
      }
    }
    if(totalCount === 0){
      message.error(`请选择商品！`);
    }else{
      const { dispatch } = this.props;
      const orderUserId = JSON.parse(localStorage.getItem("userInfo"))?JSON.parse(localStorage.getItem("userInfo")).id:null;
      const orderUserName = JSON.parse(localStorage.getItem("userInfo"))?JSON.parse(localStorage.getItem("userInfo")).name:'';
      const orderProvice = JSON.parse(localStorage.getItem("userInfo"))?JSON.parse(localStorage.getItem("userInfo")).provice:'';
      const orderCity = JSON.parse(localStorage.getItem("userInfo"))?JSON.parse(localStorage.getItem("userInfo")).city:'';
      const orderDistrict = JSON.parse(localStorage.getItem("userInfo"))?JSON.parse(localStorage.getItem("userInfo")).district:'';
      dispatch({
        type: 'order/orderSave',
        payload: {
          orderLineVOList,
          totalAmount,
          orderUserId,
          orderProvice,
          orderCity,
          orderDistrict,
          orderUserName
        },
      }).then(() => {
        const {
          order: { orderId }
        } = that.props;
        that.props.history.push({ pathname:'/demo/orderLook',state:{id : orderId,status:"CREATED"} })
      });
    }

  };

  handleFormSubmit = name => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/getGoodsList',
      payload: {
        name
      },
    });
  };



  toMyOrders = () => {
    router.push('/demo/orderlist');
  };

  renderMessage = content => (
    <Alert style={{ marginBottom: 24 }} message={content} type="error" showIcon />
  );

  changeCount = (value,item) => {
    item.quantity = value;
  };

  render() {
    const {
      order: { goodsList },
      loading,
    } = this.props;
    this.goodsList = goodsList;
    // goodsList.push(
    //   {"id":1,"rowVersion":1,"name":"士力架","number":"number001","barcode":"code001","category":"1","categoryName":"食品","brandCode":"1","brandName":"SNICKERS","description":"零食","salePrice":1.05000,"imgUrl":"https://img12.360buyimg.com/n7/jfs/t1/5849/19/2729/107447/5b975eb0Ec615051e/eeb34950512bdada.jpg"}
    // );

    const mainSearch = (
      <div style={{ textAlign: 'center' }}>
        <Input.Search
          placeholder="请输入"
          enterButton="搜索"
          size="large"
          onSearch={this.handleFormSubmit}
          style={{ maxWidth: 522, width: '100%' }}
        />
        <Button className={styles.btn} type="primary" onClick={this.handleDone}>
          去结算&gt;
        </Button>
        <a className={styles.orderLink} onClick={this.toMyOrders}>我的订单&gt;&gt;</a>
      </div>
    );

    const cardList = goodsList ? (
      <List
        rowKey="id"
        loading={loading}
        grid={{ gutter: 24,xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6}}
        dataSource={goodsList}
        renderItem={item => (
          <List.Item>
            <Card
              hoverable
              cover={<img alt={item.name} src={item.imgUrl} />}
            >
              <Card.Meta
                title={<b>{item.name}</b>}
                description={<Ellipsis lines={2}>{item.description}</Ellipsis>}
              />
              <div style={{display: 'flex',height: '20px',marginTop: '16px',marginBottom: '-4px',lineHeight: '20px'}}>
                <span style={{flex: 1,color: '@text-color-secondary',fontSize: '12px'}}>价格：{item.salePrice}元</span>
                <InputNumber precision={0} min={0} max={9999} style={{marginTop:'-5px'}} defaultValue={0} onChange={(value) => this.changeCount(value,item)} />
              </div>
            </Card>
          </List.Item>
        )}
      />
    ) : null;

    return (
      <div className={styles.main}>
        <header className={styles.header}>
          <h1>商品搜索</h1>
          {mainSearch}
        </header>
        <div className={styles.cardList}>
          {cardList}
        </div>
      </div>
    );
  }
}

export default GoodsListPage;
